#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.utils.deprecation import MiddlewareMixin
from web import models
from django.shortcuts import redirect
from django.conf import settings
import datetime


class Tracer(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """如果用户登录， 则在request赋值"""

        request.tracer = Tracer()

        # 从session中获取user_id 若无，赋值为0
        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_obj

        # 白名单: 未登录可以访问
        """
        1. 获取访问的url
        2. 检查url是否在白名单
        """
        if request.path_info in settings.WHITE_REREX_URL_LIST:
            return
        # 检查用户是否登录，已登录继续，未登录返回登录
        if not request.tracer.user:
            return redirect('login')

        # 登录成功后，获取用户的额度
        # 获取id最大的交易记录(最近交易记录)
        _object = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # 判断是否过期
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=user_obj, status=2, price_policy__category=1).first()

        request.tracer.price_policy = _object.price_policy

    def process_view(self, request, view, args, kwargs):

        # 判断url是否是以manage开头, True: 判断id是否是我的
        if not request.path_info.startswith('/manage/'):
            return
        project_id = kwargs.get('project_id')

        # 是否是我创建的
        project_obj = models.Project.objects.filter(
            creator=request.tracer.user,
            id=project_id
        ).first()
        if project_obj:
            request.tracer.project = project_obj
            return

        # 是否是我参与的
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_object:
            # 是我参与的项目
            request.tracer.project = project_user_object.project
            return

        return redirect('project_list')

